package sdk

import (
	"fmt"
	"github.com/hyperledger/fabric-sdk-go/pkg/client/msp"
	"github.com/hyperledger/fabric-sdk-go/pkg/common/providers/context"
)

type FabricCa struct {
	ctx context.ClientProvider
	cli *msp.Client
}

func (m *FabricCa) GetClient() error {
	cli, err := msp.New(m.ctx)
	if err != nil {
		return err
	}
	m.cli = cli
	return nil
}

func (m *FabricCa) AddAffiliation() error {
	cm, err := m.cli.GetCAInfo()
	if err != nil {
		return err
	}
	fmt.Println(cm)
	req := &msp.AffiliationRequest{
		Name:   "sr",
		Force:  true,
		CAName: cm.CAName,
	}
	res, err := m.cli.AddAffiliation(req)
	if err != nil {
		return err
	}
	fmt.Println(res)
	return nil
}

//
//func (m *FabricCa) EnrollUser(username string, password string) (bool, error) {
//	ctx := m.sdk.Context()
//	mspClient, err := msp.New(ctx)
//	if err != nil {
//		fmt.Printf("Failed to create msp client: %s\n", err)
//		return true, err
//	}
//
//	_, err = mspClient.GetSigningIdentity(username)
//	if err == msp.ErrUserNotFound {
//		fmt.Println("Going to enroll user")
//		err = mspClient.Enroll(username, msp.WithSecret(password))
//		if err != nil {
//			fmt.Printf("Failed to enroll user: %s\n", err)
//			return true, err
//		}
//		fmt.Printf("Success enroll user: %s\n", username)
//	} else if err != nil {
//		fmt.Printf("Failed to get user: %s\n", err)
//		return false, err
//	}
//	fmt.Printf("User %s already enrolled, skip enrollment.\n", username)
//	return true, nil
//}
//
//func (m *FabricCa) RegisterlUser(username, password, department string) error {
//	ctx := m.sdk.Context()
//	mspClient, err := msp.New(ctx)
//	if err != nil {
//		fmt.Printf("Failed to create msp client: %s\n", err)
//	}
//	request := &msp.RegistrationRequest{
//		Name:        username,
//		Type:        "user",
//		Affiliation: department,
//		Secret:      password,
//	}
//
//	secret, err := mspClient.Register(request)
//	if err != nil {
//		fmt.Printf("register %s [%s]\n", username, err)
//		return err
//	}
//	fmt.Printf("register %s successfully,with password %s\n", username, secret)
//	return nil
//}
